package com.maxd.controller.jd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.CommonInfo;
import com.maxd.model.PddOrder;
import com.maxd.model.PublisherOrderDtoBean;
import com.maxd.model.UserInfo;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.order.OrderJpaRepository;
import com.maxd.respository.order.OrderRepository;
import com.maxd.respository.pdd.PddJpaRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.utils.Config;
import com.maxd.utils.HttpClient;
//import com.pdd.pop.ext.apache.http.client.utils.URLEncodedUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jd.union.open.goods.jingfen.query.request.JFGoodsReq;
import jd.union.open.goods.jingfen.query.request.UnionOpenGoodsJingfenQueryRequest;
import jd.union.open.goods.jingfen.query.response.UnionOpenGoodsJingfenQueryResponse;
import jd.union.open.goods.promotiongoodsinfo.query.request.UnionOpenGoodsPromotiongoodsinfoQueryRequest;
import jd.union.open.goods.promotiongoodsinfo.query.response.UnionOpenGoodsPromotiongoodsinfoQueryResponse;
import jd.union.open.order.query.request.OrderReq;
import jd.union.open.order.query.request.UnionOpenOrderQueryRequest;
import jd.union.open.order.query.response.OrderResp;
import jd.union.open.order.query.response.SkuInfo;
import jd.union.open.order.query.response.UnionOpenOrderQueryResponse;
import jd.union.open.promotion.common.get.request.UnionOpenPromotionCommonGetRequest;
import jd.union.open.promotion.common.get.response.UnionOpenPromotionCommonGetResponse;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Parameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import weixin.popular.util.JsonUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

@RestController
@Api(value = "京东API管理", tags = {"京东API管理"})
@RequestMapping(value = "/jd")
public class JDController {
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private OrderJpaRepository orderJpaRepository;
    @Autowired
    private PddJpaRepository pddJpaRepository;

    @RequestMapping(value = "/goods/eliteId/{eliteId}/page/{page}/sortName/{sortName}/sort/{sort}", method = RequestMethod.GET)
    @ApiOperation("用户端获取产品列表")
    @ResponseBody
    public UnionOpenGoodsJingfenQueryResponse getGoods(@PathVariable Integer eliteId, @PathVariable Integer page, @PathVariable String sortName, @PathVariable String sort) {
        String accessToken = "";
        try {
            //京东APPID
            CommonInfo one = commonRepository.findOne(13);
            //京东秘钥
            CommonInfo two = commonRepository.findOne(14);
            JdClient client = new DefaultJdClient(Config.JD_URL, accessToken, one != null ? one.getValue() : Config.AppKey, two != null ? two.getValue() : Config.Secret);
            UnionOpenGoodsJingfenQueryRequest request = new UnionOpenGoodsJingfenQueryRequest();
            JFGoodsReq goodsReq = new JFGoodsReq();
            goodsReq.setEliteId(eliteId);
            goodsReq.setPageIndex(page);
            goodsReq.setPageSize(20);
            goodsReq.setSortName(sortName);
            goodsReq.setSort(sort);
            request.setGoodsReq(goodsReq);
            return client.execute(request);
        } catch (JdException e) {
            e.printStackTrace();
        }
        return null;
    }
   /**
     * 蚂蚁星球京东 商品列表
     api  http://api-gw.haojingke.com/index.php/v1/api/jd/goodslist?apikey=您的apikey&pageindex=1&pagesize=20
     apikey:7c2452dab2f0cc29
     secret:073fe6ee4bb14a59a8096a2c082acfeb
     * */
    @RequestMapping(value = "/jdshop")
   public class   RestTemplateExample {
        public String fetchDataUsingRestTemplate() {
            RestTemplate restTemplate = new RestTemplate();
            String url = "http://api-gw.haojingke.com/index.php/v1/api/jd/goodslist?apikey=7c2452dab2f0cc29&pageindex=1&pagesize=20";
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            String responseBody = response.getBody();
            return responseBody;
        }
    }

    @RequestMapping(value = "/goodsInfo/skuIds/{skuIds}", method = RequestMethod.GET)
    @ApiOperation("用户端获取产品详情")
    @ResponseBody
    public UnionOpenGoodsPromotiongoodsinfoQueryResponse getSkuIds(@PathVariable String skuIds) {
        String accessToken = "";
        try {
            //京东APPID
            CommonInfo one = commonRepository.findOne(13);
            //京东秘钥
            CommonInfo two = commonRepository.findOne(14);
            JdClient client = new DefaultJdClient(Config.JD_URL, accessToken, one != null ? one.getValue() : Config.AppKey, two != null ? two.getValue() : Config.Secret);
            UnionOpenGoodsPromotiongoodsinfoQueryRequest request = new UnionOpenGoodsPromotiongoodsinfoQueryRequest();
            request.setSkuIds(skuIds);
            return client.execute(request);
        } catch (JdException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/push/materialId", method = RequestMethod.GET)
    @ApiOperation("无法使用 获取推广链接")
    @ResponseBody
    public UnionOpenPromotionCommonGetResponse goodsPush(@RequestParam String materialId, @RequestParam String pid) {
        String accessToken = "";
        try {
            //京东APPID
            CommonInfo one = commonRepository.findOne(13);
            //京东秘钥
            CommonInfo two = commonRepository.findOne(14);
            JdClient client = new DefaultJdClient(Config.JD_URL, accessToken, one != null ? one.getValue() : Config.AppKey, two != null ? two.getValue() : Config.Secret);
            UnionOpenPromotionCommonGetRequest request = new UnionOpenPromotionCommonGetRequest();
            jd.union.open.promotion.common.get.request.PromotionCodeReq promotionCodeReq = new jd.union.open.promotion.common.get.request.PromotionCodeReq();
            promotionCodeReq.setMaterialId(materialId);
            promotionCodeReq.setSiteId(Config.JD_APPID);
            promotionCodeReq.setPositionId(Long.valueOf(pid));
            request.setPromotionCodeReq(promotionCodeReq);
            return client.execute(request);
        } catch (JdException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/goods/couponUrlV2", method = RequestMethod.GET)
    @ApiOperation("获取推广商品")
    @ResponseBody
    public String couponUrlV2(@RequestParam String materialId, @RequestParam String positionId,String couponUrl) {
        try {
            CommonInfo one = commonRepository.findOne(29);
            String keyid = Config.KEYID;
            if (one != null) {
                keyid = one.getValue();
            }
            CommonInfo three = commonRepository.findOne(30);
            String apkey = Config.MIAOYOUQUN_Key;
            if (three != null) {
                apkey = three.getValue();
            }
            String material = URLEncoder.encode(materialId, "utf-8");
            String url;
            if(StringUtils.isNotEmpty(couponUrl)){
                url = Config.MIAOYOUQUN_URL + "/jingdong/doItemCpsUrl?apkey=" + apkey + "&materialId=" + material + "&key_id=" + keyid + "&positionId=" + positionId + "&couponUrl=" + URLEncoder.encode(couponUrl, "utf-8");
            }else{
                url = Config.MIAOYOUQUN_URL + "/jingdong/doItemCpsUrl?apkey=" + apkey + "&materialId=" + material + "&key_id=" + keyid + "&positionId=" + positionId + "&autoSearch=1";
            }            return HttpClient.doGet(url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    @RequestMapping(value = "/goods/couponUrl", method = RequestMethod.GET)
    @ApiOperation("获取推广商品")
    @ResponseBody
    public String couponUrl(@RequestParam String materialId, @RequestParam String positionId, @RequestParam String couponUrl) {
        try {
            CommonInfo one = commonRepository.findOne(29);
            String keyid = Config.KEYID;
            if (one != null) {
                keyid = one.getValue();
            }
            CommonInfo three = commonRepository.findOne(30);
            String apkey = Config.MIAOYOUQUN_Key;
            if (three != null) {
                apkey = three.getValue();
            }
            String material = URLEncoder.encode(materialId, "utf-8");
            String url = Config.MIAOYOUQUN_URL + "/jingdong/doItemCpsUrl?apkey=" + apkey + "&materialId=" + material + "&key_id=" + keyid + "&positionId=" + positionId + "&couponUrl=" + URLEncoder.encode(couponUrl, "utf-8");
            return HttpClient.doGet(url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/goods/noCouponUrl", method = RequestMethod.GET)
    @ApiOperation("获取推广商品没有优惠券的")
    @ResponseBody
    public String noCouponUrl(@RequestParam String materialId, @RequestParam String positionId) {
        try {
            CommonInfo one = commonRepository.findOne(29);
            String keyid = Config.KEYID;
            if (one != null) {
                keyid = one.getValue();
            }
            CommonInfo three = commonRepository.findOne(30);
            String apkey = Config.MIAOYOUQUN_Key;
            if (three != null) {
                apkey = three.getValue();
            }
            String material = URLEncoder.encode(materialId, "utf-8");
            String url = Config.MIAOYOUQUN_URL + "/jingdong/doItemCpsUrl?apkey=" + apkey+ "&materialId=" + material + "&key_id=" + keyid + "&positionId=" + positionId;
            return HttpClient.doGet(url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/goods/listV2/{page}", method = RequestMethod.GET)
    @ApiOperation("通过keywords筛选商品")
    @ResponseBody
    public String getGoosListByKeyWordsV2(@PathVariable Integer page, @RequestParam String sortName, @RequestParam String keywords, @RequestParam(required = false, defaultValue = "desc") String sort) {
        try {
            CommonInfo three = commonRepository.findOne(30);
            String apkey = Config.MIAOYOUQUN_Key;
            if (three != null) {
                apkey = three.getValue();
            }
            String word = URLEncoder.encode(keywords, "utf-8");
            String url = Config.MIAOYOUQUN_URL + "/jingdong/getJdUnionItems?apkey=" + apkey + "&pageIndex=" + page + "&pageSize=20&isCoupon=0&sort=" + sort + "&keyword=" + word + "&sortName=" + sortName;
            return HttpClient.doGet(url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/goods/list/{page}", method = RequestMethod.GET)
    @ApiOperation("通过keywords筛选商品")
    @ResponseBody
    public String getGoosListByKeyWords(@PathVariable Integer page, @RequestParam String sortName, @RequestParam String keywords, @RequestParam(required = false, defaultValue = "desc") String sort) {
        try {
            CommonInfo three = commonRepository.findOne(30);
            String apkey = Config.MIAOYOUQUN_Key;
            if (three != null) {
                apkey = three.getValue();
            }
            String word = URLEncoder.encode(keywords, "utf-8");
            String url = Config.MIAOYOUQUN_URL + "/jingdong/getJdUnionItems?apkey=" + apkey + "&pageIndex=" + page + "&pageSize=20&isCoupon=1&sort=" + sort + "&keyword=" + word + "&sortName=" + sortName;
            return HttpClient.doGet(url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/goods/{skuIds}", method = RequestMethod.GET)
    @ApiOperation("通过id筛选商品")
    @ResponseBody
    public String getGoosListById(@PathVariable String skuIds) {
        CommonInfo three = commonRepository.findOne(30);
        String apkey = Config.MIAOYOUQUN_Key;
        if (three != null) {
            apkey = three.getValue();
        }
        String url = Config.MIAOYOUQUN_URL + "/jingdong/getJdUnionItems?apkey=" + apkey + "&keyword=" + skuIds;
        return HttpClient.doGet(url);
    }



    @IgnoreSecurity
    @RequestMapping(value = "/doTpwdCoverts", method = RequestMethod.GET)
    @ApiOperation("淘口令解析")
    @ResponseBody
    public String doTpwdCoverts(@RequestParam String tpwd) {
        try {
            CommonInfo three = commonRepository.findOne(30);
            CommonInfo pid = commonRepository.findOne(9);
            CommonInfo ze = commonRepository.findOne(90);
            CommonInfo tb = commonRepository.findOne(11);
            String pattern = ze.getValue();
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(tpwd);
            String group ="";
            if (m.find()) {
                group=m.group();
                System.out.println("match: " + group);
            }
            System.out.println("End");
            String apkey = Config.MIAOYOUQUN_Key;
            if (three != null) {
                apkey = three.getValue();
            }
            String tbname=tb.getValue();
            Pattern p1 = Pattern.compile("[\u4e00-\u9fa5]");
            Matcher m1 = p1.matcher(tb.getValue());
            if (m1.find()) {
                tbname= URLEncoder.encode(tb.getValue(), "utf-8");
            }
            String word = URLEncoder.encode(group, "utf-8");

            String url = Config.MIAOYOUQUN_URL + "/taoke/doTpwdCovert?apkey=" + apkey + "&pid="+pid.getValue()+"&content=" + word + "&tbname=" + tbname;
            String s = HttpClient.doGet(url);
            if (JSON.parseObject(s).getString("code").equals("200")) {
                String data = JSON.parseObject(s).getString("data");
                return JSON.parseObject(data).getString("item_id");
            }else{
                return null;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

    }


    @RequestMapping(value = "/sortUrl", method = RequestMethod.GET)
    @ApiOperation("获取短连接")
    @ResponseBody
    public String sortUrl(@RequestParam String sortUrl) {
        String url = "http://suo.nz/api.htm?format=json&url=" + sortUrl + "&key=5e69209d9f9594023280d13d@28c43a86f83a49a3d98aaa07ab5f3642";
        return HttpClient.doGet(url);
    }

}
